package org.esk.dablog.web.util;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.esk.dablog.exceptions.ParameterException;
import org.esk.dablog.ApplicationConstants;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.text.ParseException;

/**
 * This class is used to centralize request-processing routines
 * User: jc
 * Date: 30.11.2006
 * Time: 12:09:16
 * $Id:$
 */
public final class RequestUtils {

    /**
     * Extracts url-encoded parameter of type long
     * from request string like /action/1023
     *
     * @param request http request
     * @return long parameter value
     */
    public static long toLongParameter(HttpServletRequest request) {
        String id = extractStringParameter(request);
        return NumberUtils.toLong(id);
    }

    /**
     * extracts simple string parameter
     *
     * @param request
     * @return
     */
    public static String extractStringParameter(HttpServletRequest request) {
        String[] vars = StringUtils.split(request.getRequestURI(), "/");
        String id = vars[vars.length - 1];
        return id;
    }

    /**
     * Extracts url-encoded parameter of type long
     * from request string like /action/1023.
     * If parameter is not present, the ParameterException is being thrown
     *
     * @param request request
     * @return long value
     * @throws org.esk.dablog.exceptions.ParameterException
     *          exception
     */
    public static long extractLongParameter(HttpServletRequest request)
            throws ParameterException {
        long id = toLongParameter(request);
        if (id <= 0) {
            throw new ParameterException("parameter unavailable");
        }
        return id;
    }

    /**
     * extracts Date parameter
     *
     * @param request
     * @return
     * @throws ParameterException
     */
    public static Date extractDateParameter(HttpServletRequest request)
            throws ParameterException {
        Date d = null;
        try {
            d = ApplicationConstants.getInstance().getSystemDateFormat().parse(extractStringParameter(request));
        } catch (ParseException e) {
            throw new ParameterException("invalid date format", e);
        }
        return d;
    }

    /**
     * tries to extract Date parameter, returns null on error
     * @param request
     * @return
     */
    public static Date toDateParameter(HttpServletRequest request) {
        try {
            return extractDateParameter(request);
        } catch(Exception ex) {
            return null;
        }

    }
}
